package com.zhijiaoyun.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.zhijiaoyun.aliyun.oss.OSSManager;
import com.zhijiaoyun.common.*;
import com.zhijiaoyun.dao.IItemDao;
import com.zhijiaoyun.model.Item;
import com.zhijiaoyun.service.IItemService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.shisfish.util.ExcelUtil;
import com.zhijiaoyun.model.User;
import com.zhijiaoyun.service.IExcelService;
import com.zhijiaoyun.service.IUserService;

/**
 * @author shisfish
 * @date 2018/1/18
 */
@Service(value = "excelService")
public class ExcelServiceImpl implements IExcelService {

    @Resource
    IUserService userService;

    @Resource
    IItemService itemService;

    @Override
    public String exportUser() {

        List<String> headers = new ArrayList<>();
        List<String> properties = new ArrayList<>();
        List<Item> items = itemService.getByType(ItemConstant.TYPE_EXCEL_2_USER);
        if (StringUtils.isNotEmptyList(items)) {
            for (Item item : items) {
                headers.add(item.getValue());
                properties.add(item.getKey());
            }
        }

        List<User> users = userService.listAll();

        ExcelUtil<User> userExcelUtil = new ExcelUtil<>();
        XSSFWorkbook workbook = userExcelUtil.getWorkBookUser(headers, properties, users, ItemConstant.OTHER_EXCEL_USER_SHEET);

        String fileName = ItemConstant.OTHER_EXCEL_USER_SHEET + DateUtils.getDateFormat(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        String normalFilePath = CommonUtils.getProperty("normalFilePath");
        CommonUtils.checkPath(normalFilePath);
        String tempFilePath = userExcelUtil.getExportedFile(workbook, normalFilePath + fileName);
        String saveDir = CommonUtils.getProperty("excel_path");
        try {
            String filePath = OSSManager.updateFile(saveDir + fileName, new File(tempFilePath), saveDir, fileName);
            new File(tempFilePath).delete();
            return filePath;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;

    }

}
